package app.server.project.main.service.service.race;

import app.server.project.core.constants.TcpCmd;
import app.server.project.core.websocket.WSMgr;
import app.server.project.main.service.bo.event.ClickEvent;
import app.server.project.main.service.db.dao.user.RaceClickDao;
import lombok.Data;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentLinkedDeque;

@Data
@RequiredArgsConstructor(staticName = "of")
public class RaceClickTask {

    final static int MAX = 400;
    final static int FlushTime = 15;

    @NonNull
    private RaceClickDao raceClickDao;
    @NonNull
    private Integer raceId;

    private LocalDateTime pushTime;
    private ConcurrentLinkedDeque<ClickEvent> eventQueue = new ConcurrentLinkedDeque<>();

    public void add(ClickEvent clickEvent) {
        eventQueue.add(clickEvent);
    }

    public void consume() {
        //处理推送
        if (pushTime != null && LocalDateTime.now().isAfter(pushTime)) {
            var db = this.raceClickDao.getByRaceId(raceId);
            WSMgr.broadcast(TcpCmd.PK, db);
            this.pushTime = null;
        }
        int count = MAX;
        while (count > 0) {
            var clickEvent = eventQueue.pollFirst();
            if (clickEvent == null) {
                return;
            }
            var db = this.raceClickDao.getByRaceId(raceId);
            db.addClickNum(clickEvent.getNum());
            pushTime = LocalDateTime.now().plusSeconds(FlushTime);
            count--;
        }
    }
}
